--
-- Author: mm
-- Date: 2018-04-09 16:01:40
--
-- NewActivityDungeonsModel
-- 活动副本数据

local LionHornUserInfoVo = import(".LionHornUserInfoVo") -- 成员数据结构

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
end

-- 是否是狮心号角
function ClassRef:isLionHornMap()
	local mapId = MapManager:getMapId()
	return mapId == tonumber(S("lionHeartHornMapID"))
end

-- 是否是冠军赛
function ClassRef:isChampionMap()
	local mapId = MapManager:getMapId()
	if not self._throneInfo then
		self._throneInfo = GD:queryThroneByDay(app:getWeekDay())
	end

	if self._throneInfo and tonumber(self._throneInfo.mapId) == mapId then
		return true
	end
	return false
end

------------------------ receive ------------------------
local GradeEnums = {
	["NONE"] = 0,
	["COPPER"] = 1,
	["SILVER"] = 2,
	["GOLD"] = 3
}
-- 活动副本通用结算
-- message S2C_WorldEventResultNotify {
-- 	int32 id = 1; // 玩法id
-- 	int32 residualRewardTimes = 2; // 剩余奖励次数
-- 	GRADE grade = 3; // 最终评级
-- 	int32 score = 4; // 最终得分
-- 	int32 eventPoint = 5; // 获得活动点数
-- }
function ClassRef:onActivityDungeonsEnd( ret )
	local residualRewardTimes = ret.residualRewardTimes -- 剩余奖励次数

	-- 修改TeamTarget里面的剩余奖励次数
	local teamTarget = app:sendMsg("TeamModel", "getTeamTargetById", ret.id)
	if teamTarget and teamTarget:isActivity() then
		-- 剩余次数有可能是负数，服务器有用，客户端不关心，全当0处理（狮心号角有用）
		teamTarget:setRestRewardNum(math.max(residualRewardTimes, 0))
	end

	if 0 > residualRewardTimes then -- 已经没有剩余奖励次数了？
		if Enums.TeamTarget.lionHeart == ret.id then
			self:processDungeonsEnd( ret )
		else
			display.pushToast( L("ErrEventRewardNotEnough") )
			app.session:request("pb_map.C2S_BackToLastMap", {}) -- 直接请求上张地图
		end

	else
		if Enums.TeamTarget.ashInvade == ret.id and BattleManager:isInBattle() then -- 灰烬入侵 && 战斗中？
			self._activityDungeonsEnd = ret
			return
		end
		self:processDungeonsEnd( ret )
	end
end

-- 处理结算
function ClassRef:processDungeonsEnd( ret, ignoreFilter )
	ignoreFilter = ignoreFilter or false

	-- 不过滤时，灰烬入侵结算走主界面右下角提示
	if not ignoreFilter and ret.id == Enums.TeamTarget.ashInvade then
		local params = {
            remindId = Constant.FUNC_TYPE_ACTIVITY_DUNGEONS_ASHINVADE,
            dataTemp = ret
        }
        local desktopController = UIHandler:getDesktopController()
        if desktopController then
        	desktopController:insertFourthTips( params )
        end
        return
	end

	local gradeTemp = tonumber( GradeEnums[ret.grade] or 0 )
	if 0 >= gradeTemp then -- 失败？
		app:sendMsg( "NewActivityDungeonsController", "openFailView", ret )
	else
		app:sendMsg( "NewActivityDungeonsController", "openSuccessView", ret )
	end
end

-- 狮心号角回合结算
function ClassRef:onLionHornRoundEnd( ret )
	app:sendMsg( "LionHornController", "openRoundEndView", ret)
end

-- 战斗结束
function ClassRef:onBattleEnd()
	if self._activityDungeonsEnd then
		self:processDungeonsEnd( self._activityDungeonsEnd )
		self._activityDungeonsEnd = nil
	end
end

-- 冠军赛 未经战斗直接获胜
function ClassRef:onChampionWinDirectly()
	-- 在准备场
	if self:isChampionMap() then
		local msgNode = display.newMessageBox( L("lua_code_text_71") )
        UIHandler:addPopupUi(msgNode)

		-- 拉取胜负信息
		-- 拉取决赛信息
		local pvpModel = app:getInst("PvpModel")
		pvpModel:reqThroneRankInfo()
		pvpModel:reqThroneFinalTeamInfo(function()
			app:sendMsg("ChampionCopyController", "showRoundCountDown")
		end)
	end
end

------------------------ request ------------------------
-- 登陆时只拉取一次，存在TeamTarget里面，在修改的时候改一下值
function ClassRef:C2S_WorldEventInfo()
	app.session:request("pb_worldevent.C2S_WorldEventInfo", {}, function(ret)
		-- dump( ret, "C2S_WorldEventInfo ret" )

		local TeamModel = app:getInst("TeamModel")
		local teamTarget
		for i,info in ipairs( ret.infos ) do
			teamTarget = TeamModel:getTeamTargetById(info.id)
			if teamTarget and teamTarget:isActivity() then
				-- 剩余次数有可能是负数，服务器有用，客户端不关心，全当0处理（狮心号角有用）
				teamTarget:setRestRewardNum(math.max(info.residualRewardTimes, 0))
			end
		end
	end)
end


-------------------------------->>>>>>>>> 以下：狮心号角相关
-- 请求进入狮心号角
function ClassRef:reqEnterLionHorn()
	-- print( " ---------->>> reqEnterLionHorn" )
	app.session:request("pb_lionhearthorn.C2S_EnterLionHeartHorn", {}, function(ret)
		-- dump( ret, " ---------->>> reqEnterLionHorn ret" )
		app:sendMsg( "NewTeamReadyAndSettingController", "outDungeons" )
	end)
end

-- 地图加载完成：告知服务器可以开始了
function ClassRef:reqStartLionHorn()
	if not self:isLionHornMap() then return end
	-- print( " ---------->>> reqStartLionHorn" )
	app.session:request("pb_lionhearthorn.C2S_GetLionHeartHornRoundInfo", {}, function(ret)
		-- dump( ret, " ---------->>> reqStartLionHorn ret" )
		-- ret.lionHeartHornPlayerInfo 地图上玩家信息
		
		-- 已经在战斗时，不显示 回合 界面
		if BattleManager:isWaitBattle() or BattleManager:isBattle() then
			return
		end

		local lionHeartUserInfoList = {}
		for i,v in ipairs( ret.lionHeartHornPlayerInfo ) do
			local temp = LionHornUserInfoVo.new( v )
			table.insert( lionHeartUserInfoList, temp)
		end
		app:sendMsg( "LionHornController", "showLionHornRoundStart", ret, lionHeartUserInfoList)
	end)
end

-- 告知服务器：回合开始
function ClassRef:reqLionHornRoundStart()
	if not self:isLionHornMap() then return end
	-- print( " ---------->>> reqLionHornRoundStart" )
	app.session:request("pb_lionhearthorn.C2S_StartLionHeartHornRound", {}, function(ret)
		-- dump( ret, " ---------->>> reqLionHornRoundStart ret" )
	end)
end

-- 请求离开狮心号角
function ClassRef:reqLeaveLionHorn()
	-- print( " ---------->>> reqLeaveLionHorn" )
	app.session:request("pb_lionhearthorn.C2S_LeaveLionHeartHorn", {}, function(ret)
		-- dump( ret, " ---------->>> reqLeaveLionHorn ret" )
	end)
end


-------------------------------->>>>>>>>> 以下：冠军赛相关
-- 地图加载完成
function ClassRef:reqChampionInfo()
	local pvpModel = app:getInst("PvpModel")
	-- local info = pvpModel:getChampionInfo()
	-- local finalInfo = pvpModel:getFinalTeamInfo() -- 有可能冠军赛季信息有，但是决赛数据没有（通过任务界面的快捷入口进入）
	-- if info == nil or finalInfo == nil then -- 断线之后重现进入的，需要拉取冠军赛相关的几条协议
	-- 	pvpModel:reqChampionSeasonInfo()
	-- 	pvpModel:reqThroneTeamInfo()
	-- 	pvpModel:reqThroneRankInfo()
	-- 	pvpModel:reqThroneFinalTeamInfo(function()
	-- 		app:sendMsg("ChampionCopyController", "showRoundCountDown")
	-- 	end)
	-- else
	-- 	app:sendMsg("ChampionCopyController", "showRoundCountDown")
	-- end

	-- 修改为每次进准备场，都把所有信息拉取一遍，保持和服务器的同步
	pvpModel:reqChampionSeasonInfo()
	pvpModel:reqThroneTeamInfo()
	pvpModel:reqThroneRankInfo()
	pvpModel:reqThroneFinalTeamInfo(function()
		app:sendMsg("ChampionCopyController", "showRoundCountDown")
	end)
end

return ClassRef
